<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript DOM操作和事件处理</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
      line-height: 1.6;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      color: #333;
    }
    h1 {
      color: #2c3e50;
      border-bottom: 2px solid #eee;
      padding-bottom: 10px;
    }
    .example {
      background-color: #f8f9fa;
      border-left: 4px solid #42b983;
      padding: 15px;
      margin-bottom: 20px;
      border-radius: 0 4px 4px 0;
    }
    .output {
      background-color: #f1f1f1;
      padding: 10px;
      border-radius: 4px;
      margin-top: 10px;
      font-family: monospace;
      min-height: 20px;
    }
    button {
      background-color: #42b983;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 5px;
      margin-bottom: 5px;
    }
    button:hover {
      background-color: #3aa876;
    }
    .highlight {
      background-color: yellow;
      font-weight: bold;
    }
    .box {
      width: 100px;
      height: 100px;
      background-color: #3498db;
      margin: 10px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      transition: all 0.3s ease;
    }
    .form-group {
      margin-bottom: 15px;
    }
    .form-group label {
      display: block;
      margin-bottom: 5px;
    }
    .form-group input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
    .item {
      padding: 10px;
      border: 1px solid #ddd;
      margin-bottom: 5px;
      border-radius: 4px;
      cursor: pointer;
    }
    .selected {
      background-color: #e0f7fa;
      border-color: #42b983;
    }
  </style>
</head>
<body>
  <h1>JavaScript DOM操作和事件处理</h1>
  
  <div class="example">
    <h2>选择DOM元素</h2>
    <p id="target-paragraph">这是一个<span class="highlight">目标段落</span>，用于演示DOM选择器。</p>
    <p class="sample-class">这是一个带有样本类的段落。</p>
    <p class="sample-class">这是另一个带有样本类的段落。</p>
    
    <button onclick="selectById()">通过ID选择</button>
    <button onclick="selectByClass()">通过类名选择</button>
    <button onclick="selectByTag()">通过标签选择</button>
    <button onclick="selectByQuerySelector()">使用querySelector</button>
    <div id="select-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>修改DOM内容</h2>
    <div id="content-demo">原始内容</div>
    <button onclick="changeText()">修改文本</button>
    <button onclick="changeHTML()">修改HTML</button>
    <button onclick="changeAttributes()">修改属性</button>
    <div id="modify-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>修改CSS样式</h2>
    <div id="style-box" class="box">样式盒子</div>
    <button onclick="changeStyle()">修改样式</button>
    <button onclick="toggleClass()">切换类</button>
    <button onclick="resetStyle()">重置样式</button>
    <div id="style-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>创建和删除元素</h2>
    <div id="element-container"></div>
    <button onclick="createElement()">创建元素</button>
    <button onclick="appendElement()">添加元素</button>
    <button onclick="insertElement()">插入元素</button>
    <button onclick="replaceElement()">替换元素</button>
    <button onclick="removeElement()">删除元素</button>
    <div id="element-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>事件处理</h2>
    <button id="click-btn">点击我</button>
    <button id="hover-btn">悬停在我上面</button>
    <input type="text" id="input-field" placeholder="在这里输入文字">
    <div id="event-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>表单处理</h2>
    <form id="sample-form">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username">
      </div>
      <div class="form-group">
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email">
      </div>
      <button type="submit">提交</button>
    </form>
    <div id="form-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>事件委托</h2>
    <div id="item-list">
      <div class="item">项目 1</div>
      <div class="item">项目 2</div>
      <div class="item">项目 3</div>
    </div>
    <button onclick="addNewItem()">添加新项目</button>
    <div id="delegation-output" class="output"></div>
  </div>

  <script>
    // 辅助函数：将内容添加到输出区域
    function appendToOutput(outputId, content) {
      const output = document.getElementById(outputId);
      output.innerHTML += content + '<br>';
    }
    
    // 辅助函数：清空输出区域
    function clearOutput(outputId) {
      const output = document.getElementById(outputId);
      output.innerHTML = '';
    }
    
    // 选择DOM元素示例
    function selectById() {
      clearOutput('select-output');
      const element = document.getElementById('target-paragraph');
      appendToOutput('select-output', `通过ID选择: ${element.textContent.substring(0, 20)}...`);
    }
    
    function selectByClass() {
      clearOutput('select-output');
      const elements = document.getElementsByClassName('sample-class');
      appendToOutput('select-output', `通过类名选择: 找到 ${elements.length} 个元素`);
      for (let i = 0; i < elements.length; i++) {
        appendToOutput('select-output', `- 元素 ${i+1}: ${elements[i].textContent.substring(0, 20)}...`);
      }
    }
    
    function selectByTag() {
      clearOutput('select-output');
      const elements = document.getElementsByTagName('p');
      appendToOutput('select-output', `通过标签选择: 找到 ${elements.length} 个段落元素`);
    }
    
    function selectByQuerySelector() {
      clearOutput('select-output');
      const element = document.querySelector('.highlight');
      const elements = document.querySelectorAll('p');
      appendToOutput('select-output', `querySelector: ${element.textContent}`);
      appendToOutput('select-output', `querySelectorAll: 找到 ${elements.length} 个段落元素`);
    }
    
    // 修改DOM内容示例
    function changeText() {
      const element = document.getElementById('content-demo');
      element.textContent = '文本已被修改！';
      appendToOutput('modify-output', '使用textContent修改了文本');
    }
    
    function changeHTML() {
      const element = document.getElementById('content-demo');
      element.innerHTML = '包含<strong>HTML</strong>的内容';
      appendToOutput('modify-output', '使用innerHTML修改了HTML内容');
    }
    
    function changeAttributes() {
      const element = document.getElementById('content-demo');
      element.setAttribute('data-custom', '自定义属性值');
      element.title = '鼠标悬停提示';
      appendToOutput('modify-output', `添加了属性: data-custom="${element.getAttribute('data-custom')}"`);
      appendToOutput('modify-output', `添加了属性: title="${element.title}"`);
    }
    
    // 修改CSS样式示例
    function changeStyle() {
      clearOutput('style-output');
      const box = document.getElementById('style-box');
      box.style.backgroundColor = '#e74c3c';
      box.style.width = '150px';
      box.style.height = '150px';
      box.style.borderRadius = '50%';
      appendToOutput('style-output', '直接修改了元素的样式');
    }
    
    function toggleClass() {
      clearOutput('style-output');
      const box = document.getElementById('style-box');
      box.classList.toggle('highlight');
      if (box.classList.contains('highlight')) {
        appendToOutput('style-output', '添加了highlight类');
      } else {
        appendToOutput('style-output', '移除了highlight类');
      }
    }
    
    function resetStyle() {
      clearOutput('style-output');
      const box = document.getElementById('style-box');
      box.removeAttribute('style');
      box.className = 'box';
      appendToOutput('style-output', '重置了元素的样式');
    }
    
    // 创建和删除元素示例
    function createElement() {
      clearOutput('element-output');
      window.newParagraph = document.createElement('p');
      newParagraph.textContent = '这是一个新创建的段落元素。';
      newParagraph.className = 'new-element';
      appendToOutput('element-output', '创建了新的段落元素（尚未添加到DOM）');
    }
    
    function appendElement() {
      clearOutput('element-output');
      if (!window.newParagraph) {
        createElement();
      }
      const container = document.getElementById('element-container');
      container.appendChild(newParagraph);
      appendToOutput('element-output', '将新元素添加到容器末尾');
    }
    
    function insertElement() {
      clearOutput('element-output');
      const container = document.getElementById('element-container');
      const insertP = document.createElement('p');
      insertP.textContent = '这是一个插入的段落。';
      insertP.className = 'inserted-element';
      
      if (container.firstChild) {
        container.insertBefore(insertP, container.firstChild);
        appendToOutput('element-output', '在容器的开头插入了新元素');
      } else {
        container.appendChild(insertP);
        appendToOutput('element-output', '容器为空，添加了新元素');
      }
    }
    
    function replaceElement() {
      clearOutput('element-output');
      const container = document.getElementById('element-container');
      
      if (container.firstChild) {
        const replaceP = document.createElement('p');
        replaceP.textContent = '这是一个替换的段落。';
        replaceP.className = 'replaced-element';
        
        container.replaceChild(replaceP, container.firstChild);
        appendToOutput('element-output', '替换了第一个子元素');
      } else {
        appendToOutput('element-output', '容器为空，无法替换元素');
      }
    }
    
    function removeElement() {
      clearOutput('element-output');
      const container = document.getElementById('element-container');
      
      if (container.firstChild) {
        container.removeChild(container.firstChild);
        appendToOutput('element-output', '移除了第一个子元素');
      } else {
        appendToOutput('element-output', '容器为空，无法移除元素');
      }
    }
    
    // 事件处理示例
    document.addEventListener('DOMContentLoaded', function() {
      const clickBtn = document.getElementById('click-btn');
      const hoverBtn = document.getElementById('hover-btn');
      const inputField = document.getElementById('input-field');
      const eventOutput = document.getElementById('event-output');
      
      // 点击事件
      clickBtn.addEventListener('click', function(event) {
        eventOutput.innerHTML = `点击事件触发于: ${new Date().toLocaleTimeString()}<br>`;
        eventOutput.innerHTML += `事件类型: ${event.type}<br>`;
        eventOutput.innerHTML += `目标元素: ${event.target.tagName}<br>`;
      });
      
      // 鼠标事件
      hoverBtn.addEventListener('mouseenter', function() {
        eventOutput.innerHTML = '鼠标进入按钮';
        this.style.backgroundColor = '#e74c3c';
      });
      
      hoverBtn.addEventListener('mouseleave', function() {
        eventOutput.innerHTML = '鼠标离开按钮';
        this.style.backgroundColor = '#42b983';
      });
      
      // 输入事件
      inputField.addEventListener('input', function() {
        eventOutput.innerHTML = `当前输入: ${this.value}`;
      });
      
      inputField.addEventListener('focus', function() {
        this.style.borderColor = '#42b983';
        this.style.outline = 'none';
        this.style.boxShadow = '0 0 5px rgba(66, 185, 131, 0.5)';
      });
      
      inputField.addEventListener('blur', function() {
        this.style.borderColor = '#ddd';
        this.style.boxShadow = 'none';
      });
      
      // 表单处理
      const sampleForm = document.getElementById('sample-form');
      const formOutput = document.getElementById('form-output');
      
      sampleForm.addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单提交
        
        const username = this.elements.username.value;
        const email = this.elements.email.value;
        
        let isValid = true;
        let errorMessage = '';
        
        if (!username) {
          isValid = false;
          errorMessage += '用户名不能为空<br>';
        }
        
        if (!email) {
          isValid = false;
          errorMessage += '邮箱不能为空<br>';
        } else if (!email.includes('@')) {
          isValid = false;
          errorMessage += '邮箱格式不正确<br>';
        }
        
        if (isValid) {
          formOutput.innerHTML = `表单提交成功！<br>用户名: ${username}<br>邮箱: ${email}`;
          this.reset(); // 重置表单
        } else {
          formOutput.innerHTML = `表单验证失败:<br>${errorMessage}`;
        }
      });
      
      // 事件委托
      const itemList = document.getElementById('item-list');
      const delegationOutput = document.getElementById('delegation-output');
      
      itemList.addEventListener('click', function(event) {
        if (event.target.classList.contains('item')) {
          // 切换选中状态
          event.target.classList.toggle('selected');
          
          // 更新输出
          const selectedItems = document.querySelectorAll('.item.selected');
          delegationOutput.innerHTML = `已选中 ${selectedItems.length} 个项目`;
        }
      });
    });
    
    // 添加新项目（用于事件委托示例）
    function addNewItem() {
      const itemList = document.getElementById('item-list');
      const itemCount = itemList.children.length + 1;
      
      const newItem = document.createElement('div');
      newItem.className = 'item';
      newItem.textContent = `项目 ${itemCount}`;
      
      itemList.appendChild(newItem);
      document.getElementById('delegation-output').innerHTML = `添加了新项目: 项目 ${itemCount}`;
    }
  </script>
</body>
</html>